package org.lzy.shop.activity

import android.content.ContentValues
import android.content.Intent
import android.net.Uri
import android.provider.MediaStore
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.graphics.toColorInt
import com.google.android.material.textview.MaterialTextView
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.XXPermissions
import com.hjq.permissions.permission.PermissionLists
import com.hjq.permissions.permission.base.IPermission
import com.kongzue.dialogx.dialogs.CustomDialog
import com.kongzue.dialogx.interfaces.OnBindView
import org.lzy.shop.BuildConfig
import org.lzy.shop.R
import org.lzy.shop.address.AddressListActivity
import org.lzy.shop.base.BaseMvvmActivity
import org.lzy.shop.databinding.ActivityPersoninfoBinding
import org.lzy.shop.util.DataStoreUtils
import org.lzy.shop.util.FileManager
import org.lzy.shop.util.setFileUrl
import org.lzy.shop.util.setUrlRound
import org.lzy.shop.viewmodel.MineModel
import java.io.File

/**
 * 个人中心
 * - 性别设置
 * - 生日设置
 * - 个性签名
 * - 实名认证状态
 * - 我的收藏
 * - 浏览历史
 * - 消息通知开关
 * - 清除缓存
 * - 隐私设置入口
 * - 通用设置入口
 * - 帮助与反馈
 * - 关于我们
 */

class PersonInfoActivity: BaseMvvmActivity<ActivityPersoninfoBinding, MineModel>({ ActivityPersoninfoBinding.inflate(it) }) {
    //相机拍照URI
    private var photoUri: Uri? = null


    //保存的头像路径
    private var saveAvatarPath: String? = null

    //拍照回调
    var mActivityResultLauncherTake: ActivityResultLauncher<Intent>? = null

    //相册回调
    var mActivityResultLauncherAlbum: ActivityResultLauncher<Intent>? = null



    override fun initView() {
        setTitleText(getResString(R.string.person_info))
        binding.showVer.text = BuildConfig.VERSION_NAME
        registerActivityResult()
    }

    override fun requestData() {
        mViewModel.getMyInfo()
    }

    override fun initData() {
        mViewModel.myData.observeWithLifecycle(this){myInfoResponse ->
            myInfoResponse?.let {
                binding.nickname.text = myInfoResponse.nickName
                binding.mobile.text = myInfoResponse.phone
                binding.account.text = myInfoResponse.id
                setUrlRound(myInfoResponse.avatarUrl,80f,binding.mineIvIcon)
            }
        }
        //注销账户后回调
        mViewModel.logoutData.observeWithLifecycle(this){
            dismissLoading()
            showSuccessToast(getResString(R.string.logout_success))
            DataStoreUtils.clearAll()
            startActivity(LoginActivity::class.java)
            finish()
        }
    }

    private fun registerActivityResult() {
        mActivityResultLauncherTake = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == RESULT_OK) {
                // 拍照后直接设置头像，不裁剪
                photoUri?.let {
                    setAvatar(it)
                }
            }
        }

        mActivityResultLauncherAlbum = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == RESULT_OK) {
                result.data?.data?.let {
                    setAvatar(it)
                }
            }
        }
    }

    /**
     * 设置用户头像
     */
    private fun setAvatar(imageUri: Uri) {
        try {
            val file: File? = FileManager.getMediaUri2File(this,imageUri)
            saveAvatarPath = file?.absolutePath
            // 使用setFileUrl设置图片，避免直接加载大图片导致OOM
            setFileUrl(file, binding.mineIvIcon)
        } catch (e: Exception) {

        }
    }


    /**
     * 调取本地相机拍照
     */
    private fun takePictures() {
        val takeIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        val values = ContentValues()
        //根据uri查询图片地址
        photoUri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
        if (photoUri != null) {
            //放入拍照后的地址
            takeIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri)
            //调起拍照
            mActivityResultLauncherTake?.launch(takeIntent)
        }
    }

    private fun  openAlbum(){
        val intentAlbum= Intent(Intent.ACTION_PICK, null)
        intentAlbum.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*")
        mActivityResultLauncherAlbum?.launch(intentAlbum)
    }

        override fun allClick() {
            //点击地址管理
        binding.addressManagerLayout.setOnClickListener {
            startActivity(AddressListActivity::class.java)
        }

        //点击用户头像
        binding.myUsericonLayout.setOnClickListener {
            XXPermissions.with(this)
                // 申请多个权限
                .permission(PermissionLists.getManageExternalStoragePermission())
                .permission(PermissionLists.getCameraPermission())
                // 设置不触发错误检测机制（局部设置）
                //.unchecked()
                .request(object : OnPermissionCallback {

                    override fun onGranted(permissions: MutableList<IPermission>, allGranted: Boolean) {
                        if (!allGranted) {

                            return
                        }
                        CustomDialog.show(object : OnBindView<CustomDialog?>(R.layout.dialog_choosepic) {
                            override fun onBind(dialog: CustomDialog?, v: View?) {
                                val camera = v?.findViewById<MaterialTextView>(R.id.camera)
                                val album = v?.findViewById<MaterialTextView>(R.id.album)
                                val btnCancel = v?.findViewById<MaterialTextView>(R.id.cancel)
                                //拍照
                                camera?.setOnClickListener {
                                    takePictures()
                                }
                                //相册
                                album?.setOnClickListener {
                                    openAlbum()
                                }
                                btnCancel?.setOnClickListener { dialog?.dismiss() }
                            }
                        }).setMaskColor("#4D000000".toColorInt())
                    }

                    override fun onDenied(permissions: MutableList<IPermission>, doNotAskAgain: Boolean) {
                        if (doNotAskAgain) {

                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(this@PersonInfoActivity, permissions)
                        } else {

                        }
                    }
                })

            }
    }

    // 处理内存泄漏问题
    override fun onDestroy() {
        super.onDestroy()
        // 清除引用，避免内存泄漏
        mActivityResultLauncherTake = null
        mActivityResultLauncherAlbum = null
        photoUri = null
        saveAvatarPath = null
    }
}